package com.bupt.smart.ui.activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import com.bupt.smart.model.Market;
import com.bupt.smart.model.recAddress;
import com.bupt.smart.smart.*;
import com.bupt.smart.ui.adapter.AddressAdapter;
import com.bupt.smart.ui.adapter.MarketAdapter;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by HH on 2016/4/14.
 */
public class OrderActivity extends AppCompatActivity implements View.OnClickListener{
    recAddress data;//收货地址
    private String strPrice;//订单总价
    private int totalnum;//订单中的商品总数
    private String strMarketID;//商店ID
    private String strMarketName;//商店名称
    private String strPrivilege;//商店优惠
    HashMap<String,HashMap<String,String>> orderinfo;
    private SimpleAdapter adapter;
    private TextView tvMarketName;
    private String zhifujine;
    private String dingdanname;
    private ImageView ivAddAddr;
    private ImageView ivBack;
    private ImageView ivRemark;
    private Button button;
    private Spinner spinner_time;
    private Spinner spinner_date;
    private TextView tvPrice;
    private ArrayAdapter<String> adapterDate;
    private ArrayAdapter<String> adapterTime;
    LinearLayout layoutAddress;
    LinearLayout layoutShowAddress;
    ImageButton ibChangeAddr;
    TextView tvShowAddr;
    Intent getIntent;
    private Market marketInfo;
    /*
    * orderinof:
    * key:商品ID
    * value: HashMap:num 商品数量   name 商品名称   price 商品单价
    * */
    protected void onCreate( Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order);
        getIntent = getIntent();
        HashMap<String,HashMap<String,String>> orderinfo = (HashMap<String,HashMap<String,String>>)getIntent.getSerializableExtra("orderInfo");

        //商家信息:商家ID，名称，优惠情况，订单总价
        marketInfo = (Market)getIntent.getSerializableExtra("market");
        layoutAddress = (LinearLayout)findViewById(R.id.layout_addAddress);
        tvShowAddr = (TextView)findViewById(R.id.showAddress);
        strMarketName = marketInfo.getmarketname();
        strMarketID = marketInfo.getID()+"";
        strPrivilege = marketInfo.getmarketyouhui();
        strPrice = getIntent.getStringExtra("totalprice");

        //获取当前orderlayout中的这些元素
        ibChangeAddr = (ImageButton)findViewById(R.id.btn_changeAddress);
        ivAddAddr = (ImageView)findViewById(R.id.addshouhuodizhi);
        tvMarketName = (TextView)findViewById(R.id.marketName);
        ListView view_order = (ListView) findViewById(R.id.category_list);
        spinner_time = (Spinner)findViewById(R.id.ordertime);
        spinner_date = (Spinner)findViewById(R.id.orderdate);
        tvPrice = (TextView)findViewById(R.id.dingdanzongjia);
        Button button = (Button) findViewById(R.id.order_defineorder);
        ivBack = (ImageView)findViewById(R.id.order_back);
        ivRemark = (ImageView)findViewById(R.id.order_beizhu);
        layoutShowAddress = (LinearLayout)findViewById(R.id.layout_showAddress);

        //setText赋给他们从marketActivity中传过来的值
        tvPrice.setText(strPrice);
        tvMarketName.setText(strMarketName);//显示商家名称
        String[] dates = {"今天","明天","后天"};
        tvShowAddress(getIntent);//添加收货地址/编辑收货地址
        adapterDate = new ArrayAdapter<String>(this,R.layout.spinner_orderspinner,dates);
        adapterDate.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner_date.setAdapter(adapterDate);
        adapterTime = initSpinner(spinner_date, this);
        spinner_time.setAdapter(adapterTime);
        //根据配送日期修改可选配送时间
        spinner_date.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                //定义adapterTime
                adapterTime = initSpinner(spinner_date, getBaseContext());
                //将该adapter赋给spinner_time
                spinner_time.setAdapter(adapterTime);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        //显示订单信息：数量，名称，单价
        view_order.setAdapter(
                new SimpleAdapter(
                        this,
                        getOrderList(orderinfo),
                        R.layout.listview_order,
                        new String[]{"num", "name", "price"},
                        new int[]{R.id.ordernum, R.id.ordername, R.id.orderprice}));

        //跳转支付界面
        button.setOnClickListener(this);
        //添加收货地址
        ivAddAddr.setOnClickListener(this);
        //修改收货地址
        ibChangeAddr.setOnClickListener(this);
        //跳转至备注页面
        ivRemark.setOnClickListener(this);
        //返回商家详情页面
        ivBack.setOnClickListener(this);


    }
    //获取订单详情数据
    public static List<Map<String,String>> getOrderList(HashMap<String,HashMap<String,String>> orderlist){
        if(orderlist != null){
            List<Map<String,String>> list = new ArrayList<Map<String,String>>();
            Map<String,String> temp;
            for(String key:orderlist.keySet()){
                temp = new HashMap<String,String>();
                temp = (HashMap<String,String>) orderlist.get(key).clone();
                list.add(temp);
            }
            return list;
        }
        else
            return null;
    }
    //获取地址信息并显示，null显示“添加收货地址”
    public void tvShowAddress(Intent intent){
        Bundle bundle = intent.getBundleExtra("address");
        if(bundle==null){
            Log.i("bundle","null");
            //显示“添加收货地址”
            layoutAddress.setVisibility(View.VISIBLE);
            layoutShowAddress.setVisibility(View.GONE);
        }
        //解析收货地址
        else{
            data = (recAddress)bundle.get("address");
            String address = "收货人: "+data.getName()+"    Tel: "+data.getPhonenumber()+" \n地址: "+data.getBuilding()+"号楼"+data.getHousenumber();
            tvShowAddr.setText(address);
            Log.i("bundle", address);
            layoutShowAddress.setVisibility(View.VISIBLE);
            layoutAddress.setVisibility(View.GONE);
        }

    }
    //初始化送货时间spinner
    public static ArrayAdapter<String> initSpinner(Spinner spinner_date,Context context){
        String[] times;
        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);//获取当前系统时间
        Log.i("hour",hour+"");
        String date = (String)spinner_date.getSelectedItem();
        if(date.equals("今天")){
            if(hour>=8&&hour<20){
                times = new String[20-hour];
                for(int i=0;i<times.length;i++){
                    times[i] = (++hour)+":00";
                }
            }
            else if(hour>=20){
                times = new String[1];
                times[0] = "结束";
            }
            else {
                times = new String[13];
                for(int i=0;i<times.length;i++)
                    times[i] = (i+8)+":00";
            }
        }
        else{
            times = new String[13];
            for(int i=0;i<times.length;i++)
                times[i] = (i+8)+":00";
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                context,R.layout.spinner_orderspinner,
                times);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        return adapter;

    }
    //触发事件
    @Override
    public void onClick(View v){
        switch(v.getId()){
            case R.id.addshouhuodizhi:{ //添加收货地址
                Intent intent = new Intent(OrderActivity.this,AddressActivity.class);
                intent.putExtras(getIntent);
                OrderActivity.this.startActivity(intent);
            }break;
            case R.id.btn_changeAddress:{   //修改收货地址
                Intent intent = new Intent(OrderActivity.this,AddressActivity.class);
                intent.putExtras(getIntent);
                OrderActivity.this.startActivity(intent);

            }break;
            case R.id.order_beizhu:{    //添加订单备注
                Intent intent = new Intent(OrderActivity.this,CommentActivity.class);
                intent.putExtras(getIntent);
                OrderActivity.this.startActivity(intent);
            }break;
            case R.id.order_back:{  //返回购买界面
                Intent intent = new Intent(OrderActivity.this,MarketActivity.class);
                intent.putExtras(getIntent);
                OrderActivity.this.startActivity(intent);
            }break;
            case R.id.order_defineorder:{   //提交订单
                Intent intent = new Intent(OrderActivity.this,PaymentActivity.class);
                intent.putExtras(getIntent);
//                intent.putExtra("shopID", strMarketID);
//                intent.putExtra("order_youhui", strPrivilege);
//                intent.putExtra("order_name", strMarketName);
//                intent.putExtra("order_price", strPrice);
                OrderActivity.this.startActivity(intent);
            }break;
            default:{}
        }
    }


}
